import { OneModal } from '@/components/one-ui';
import React, { Ref, useRef, useState, useMemo } from 'react';
import { IOneModalRef } from '@/pages/type';
import { Button, Spin, message, Steps, Space } from 'antd';
import { MaterialManageAPI } from '../common/type';
import { getCompanyID, getPosIDs, getUserDepID, getUserID, onCloseModalCommon } from '@/utils';
import { batchAddMaterialServices } from '../services';
import cls from 'classnames';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { UploadFirstStep } from './UploadFirstStep';
import { UploadSecordStep } from './UploadSecordStep';
import { UploadThirdStep } from './UploadThirdStep';

export const UploadModal: React.FC<MaterialManageAPI.IUploadModal> = ({ curRes, onClose, reloadManage }) => {
  const prefix = 'material-upload-';

  /** 子组件表单ref  第二步步骤 */
  const uploadFormRef = useRef<MaterialManageAPI.IUploadFormRef>(null);

  /** 定义步骤 */
  const steps = [
    {
      title: '上传文件',
    },
    {
      title: '数据校验',
    },
    {
      title: '上传完成',
    },
  ];

  /**弹框的ref*/
  const uploadModalRef: Ref<IOneModalRef> = useRef(null);

  /** 当前步骤 */
  const [current, setCurrent] = useState<number>(0);

  /** 保存导入的数据 */
  const [uploadList, setUploadList] = useState<Record<string, any>[]>([]);

  /**点击确定方法*/
  const onUploadOK = () => {
    uploadFormRef?.current?.secordStepForm?.validateFields()?.then((values: any) => {
      if (values?.table !== undefined && typeof values?.table[Symbol.iterator] === 'function') {
        let dataSource = [...values?.table];
        dataSource?.forEach((item) => {
          item.state = 2;
          item.signState = 1;
          item.signType = 0;
          item.signerID = getUserID();
          item.signPositionID = getPosIDs();
          item.signDepartmentID = getUserDepID();
          item.signCompanyID = getCompanyID();
        });
        if (!dataSource?.length) {
          console.log('暂无数据可导入，请重新上传文件！');
          return;
        }
        let reqObj = { mmaterialList: dataSource };
        batchAddMaterialRun(reqObj);
      } else {
        message.error('未上传文件或文件解析错误');
      }
    });
  };

  /**点击取消方法*/
  const onUploadCancel = () => {
    onCloseModalCommon(uploadModalRef);
  };

  /**点击确认方法*/
  const onUploadSure = () => {
    reloadManage();
    onCloseModalCommon(uploadModalRef);
  };

  /**批量添加Callback*/
  const batchAddMaterialCallback = (res: any) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      // onCloseModalCommon(uploadModalRef);
      reloadManage();
      setCurrent(2);
    }
  };

  /**添加方法services*/
  const { batchAddMaterialRun, batchAddMaterialLoading, batchAddMaterialData } = batchAddMaterialServices(batchAddMaterialCallback);

  /**监听有无数据 有数据下一步按钮不禁用*/
  const allUploadList = useMemo(() => {
    if (uploadList && uploadList?.length > 0) {
      return true;
    }
    return false;
  }, [uploadList]);

  /**公用loading*/
  const allLoading = useMemo(() => {
    return false;
  }, [current]);

  /** 请求完批量接口  如果有数据 自动跳到最后一步 */
  // useEffect(() => {
  //   if (batchAddMaterialData && batchAddMaterialData?.length > 0) {
  //     setCurrent(2);
  //   }
  // }, [batchAddMaterialData]);

  /** 更新导入的数据 */
  const reloadUploadList = (dataInfo: Record<string, any>[]) => {
    setUploadList(dataInfo);
  };

  /** 底部按钮 */
  const footerModal = useMemo(() => {
    return (
      <div className={cls(prefix + 'footer')}>
        <Space>
          <Button key="back" onClick={onUploadCancel}>
            关闭
          </Button>

          {current === 0 && (
            <Button
              type="primary"
              onClick={() => {
                if (allUploadList) {
                  setCurrent(1);
                } else {
                  message.error('未上传文件或文件解析错误');
                }
              }}
            >
              下一步
            </Button>
          )}
          {current === 1 && (
            <>
              <Button
                onClick={() => {
                  setCurrent(0);
                }}
                type="primary"
              >
                上一步
              </Button>

              <Button key="submit" type="primary" loading={allLoading} onClick={onUploadOK}>
                确认
              </Button>
            </>
          )}
          {current === 2 && (
            <>
              <Button type="primary" onClick={onUploadSure}>
                确认
              </Button>
            </>
          )}
        </Space>
      </div>
    );
  }, [curRes, current, allLoading, allUploadList]);

  /**改变步骤条 */
  const handleChangeSteps = (current: number) => {
    if (current === 0) {
      setUploadList(uploadList);
      setCurrent(0);
    } else if (current === 1) {
      setUploadList(uploadList);
      setCurrent(1);
    } else if (current === 2) {
      setCurrent(2);
    }
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={uploadModalRef}
        title={'导入文件'}
        onCancel={onClose}
        onOk={onUploadOK}
        footer={footerModal}
        width={document.body.clientWidth * 0.7}
        bodyStyle={{
          height: document.body.clientHeight * 0.55,
          padding: '5px 10px',
        }}
        centered
      >
        <Spin spinning={allLoading || batchAddMaterialLoading}>
          <div
            className={'material-upload'}
            style={{
              padding: '0 30px',
              height: '100%',
              overflow: 'hidden',
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            <div className={cls(prefix + 'step')}>
              <Steps current={current} size={'small'} items={steps} />
            </div>
            <div className={cls(prefix + 'content')}>
              <ScrollBarLayout>
                <div className={current == 0 ? '' : 'materialBatchImportCls'} style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
                  <UploadFirstStep prefix={prefix} current={current} reloadUploadList={reloadUploadList} handleChangeSteps={handleChangeSteps} />
                </div>
                <div className={current == 1 ? '' : 'materialBatchImportCls'} style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
                  <UploadSecordStep prefix={prefix} current={current} tableList={uploadList} ref={uploadFormRef} handleChangeSteps={handleChangeSteps} />
                </div>
                <div className={current == 2 ? '' : 'materialBatchImportCls'} style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
                  <UploadThirdStep prefix={prefix} current={current} total={batchAddMaterialData?.length || uploadList?.length || 0} />
                </div>
              </ScrollBarLayout>
            </div>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
